//! 实时通信模块 - 替代 C# DataShare 的 SignalR 功能
//! 提供基于 WebSocket 和 Server-Sent Events 的实时通信服务

pub mod websocket;
pub mod sse;
pub mod connection;
pub mod message;
pub mod hub;
pub mod handlers;

// 重新导出主要类型
pub use websocket::WebSocketHandler;
pub use sse::SSEHandler;
pub use connection::{ConnectionManager, ConnectionId};
pub use message::{HubMessage, HubResponse};
pub use hub::DataHub;

use crate::models::token_model::TokenModel;
use crate::models::operate_result::OperateResult;
use serde_json::Value;

/// 实时通信服务配置
#[derive(Debug, Clone)]
pub struct RealtimeConfig {
    pub websocket_path: String,
    pub sse_path: String,
    pub max_connections: usize,
    pub heartbeat_interval: u64,
    pub timeout_duration: u64,
}

impl Default for RealtimeConfig {
    fn default() -> Self {
        Self {
            websocket_path: "/ws".to_string(),
            sse_path: "/sse".to_string(),
            max_connections: 1000,
            heartbeat_interval: 30, // 30秒
            timeout_duration: 300, // 5分钟
        }
    }
}

/// 实时通信服务
pub struct RealtimeService {
    pub config: RealtimeConfig,
    pub connection_manager: ConnectionManager,
    pub data_hub: DataHub,
}

impl RealtimeService {
    pub fn new(config: RealtimeConfig) -> Self {
        let connection_manager = ConnectionManager::new(config.max_connections);
        let data_hub = DataHub::new();
        
        Self {
            config,
            connection_manager,
            data_hub,
        }
    }
    
    /// 启动实时通信服务
    pub async fn start(&self) -> anyhow::Result<()> {
        tracing::info!("启动实时通信服务");
        Ok(())
    }
    
    /// 停止实时通信服务
    pub async fn stop(&self) -> anyhow::Result<()> {
        tracing::info!("停止实时通信服务");
        Ok(())
    }
}

/// 消息处理器 trait
#[async_trait::async_trait]
pub trait MessageHandler: Send + Sync {
    /// 处理消息
    async fn handle_message(&self, 
                          message: HubMessage, 
                          token: Option<TokenModel>) -> anyhow::Result<HubResponse>;
    
    /// 获取处理器名称
    fn name(&self) -> &'static str;
}

/// 连接事件
#[derive(Debug, Clone)]
pub enum ConnectionEvent {
    Connected(ConnectionId),
    Disconnected(ConnectionId),
    MessageReceived(ConnectionId, HubMessage),
    Error(ConnectionId, String),
}

/// 连接事件处理器
#[async_trait::async_trait]
pub trait ConnectionEventHandler: Send + Sync {
    async fn on_event(&self, event: ConnectionEvent);
}